import React, {useEffect, useState} from 'react';
import {
    AppBar,
    Box,
    Collapse,
    Drawer,
    IconButton,
    List,
    ListItemButton,
    ListItemIcon,
    ListItemText,
    Slide,
    Tab,
    Tabs,
    Toolbar,
    Typography,
} from '@mui/material';

import AccountCircle from '@mui/icons-material/AccountCircle';
import ChevronLeftIcon from '@mui/icons-material/ChevronLeft';
import CloseIcon from '@mui/icons-material/Close';
import ExitToApp from '@mui/icons-material/ExitToApp';
import ExpandLess from '@mui/icons-material/ExpandLess';
import ExpandMore from '@mui/icons-material/ExpandMore';
import MenuIcon from '@mui/icons-material/Menu';
import Icon from '@mui/material/Icon';
import 'material-icons/iconfont/material-icons.css';

import {useNavigate} from 'react-router-dom';
import store, {logout} from './redux/store';
import {logout as logoutApi} from "./api/common/logout";

import Todo from './components/todo';

import {getMenu, MyContext, userinfo, welcome} from "./menu";

const drawerWidth = 200;

const App = () => {

    const {token, user} = store.getState().auth;

    const navigate = useNavigate();

    useEffect(() => {
        if (token === null) {
            navigate('/login');
            return;
        }
        document.title = 'Train';
    }, [token, navigate]);

    const menus = getMenu(user?.role) || [];

    const [openMenuList, setOpenMenuList] = useState([welcome]);
    const [activeMenu, setActiveMenu] = useState(welcome);

    const [menuOpen, setMenuOpen] = useState(true);
    const [expandedMenu, setExpandedMenu] = useState('');
    const [selectedMenu, setSelectedMenu] = useState('welcome'); // State for selected menu item

    const handleDrawerToggle = () => {
        setMenuOpen(!menuOpen);
    };

    const handleTabChange = (event, newValue) => {
        const menu = openMenuList.find(e => e.key === newValue);
        if (menu) {
            setActiveMenu(menu);
            setSelectedMenu(menu.key);
            const parentMenu = menus.find(e => e.children && e.children.some(child => child.key === menu.key));
            if (parentMenu) {
                setExpandedMenu(parentMenu.key);
            }
        }
    };

    const handleTabClose = (tab) => {

        const len = openMenuList.length;
        const index = openMenuList.findIndex(e => e.key === tab);

        const rest = openMenuList.filter(e => e.key !== tab);
        setOpenMenuList(rest);

        if (activeMenu.key === tab) {
            if (index === len - 1) {
                setActiveMenu(rest[rest.length - 1]);
            } else {
                setActiveMenu(rest[index]);
            }
        }
    };

    const handleMenuClick = (menu) => {
        setSelectedMenu(menu.key); // Set the selected menu item
        const open = openMenuList.find(e => e.key === menu.key);
        if (!open) {
            setOpenMenuList([...openMenuList, menu]);
        }
        setActiveMenu(menu);
    };

    const handleFirstLevelMenuClick = (menuKey) => {
        setExpandedMenu(expandedMenu === menuKey ? '' : menuKey);
    };

    const handleLogout = async () => {
        await logoutApi();
        store.dispatch(logout());
        navigate('/login');
    };

    const handleUserinfo = () => {
        handleMenuClick(userinfo);
    };

    return (token == null ? null :
            <Box sx={{display: 'flex'}}>
                {Boolean(menus.length) &&
                    <Slide direction="right" in={menuOpen} mountOnEnter unmountOnExit>
                        <Drawer variant="persistent" open={menuOpen}
                                sx={{
                                    width: drawerWidth,
                                    flexShrink: 0,
                                    '& .MuiDrawer-paper': {width: drawerWidth, boxSizing: 'border-box'},
                                }}
                        >
                            <List>
                                {menus.map(menu => (
                                    <React.Fragment key={menu.key}>
                                        <ListItemButton onClick={() => handleFirstLevelMenuClick(menu.key)}
                                                        selected={selectedMenu === menu.key ||
                                                            menu.children.find(child => child.key === selectedMenu) !== undefined}>
                                            <ListItemIcon>
                                                <Icon>{menu.icon}</Icon>
                                            </ListItemIcon>
                                            <ListItemText primary={menu.name}/>
                                            {expandedMenu === menu.key ? <ExpandLess/> : <ExpandMore/>}
                                        </ListItemButton>

                                        <Collapse in={expandedMenu === menu.key} timeout="auto" unmountOnExit>
                                            <List component="div" disablePadding>
                                                {menu.children.map(child => (
                                                    <ListItemButton key={child.key} sx={{pl: 4}}
                                                                    onClick={() => handleMenuClick(child)}
                                                                    selected={selectedMenu === child.key}>
                                                        <ListItemIcon>
                                                            <Icon>{child.icon}</Icon>
                                                        </ListItemIcon>
                                                        <ListItemText primary={child.name}/>
                                                    </ListItemButton>
                                                ))}
                                            </List>
                                        </Collapse>
                                    </React.Fragment>
                                ))}
                            </List>
                        </Drawer>
                    </Slide>
                }
                <Box sx={{
                    flexGrow: 1,
                    transition: 'width 225ms ease-in-out',
                    height: '100vh',
                    display: 'flex',
                    flexDirection: 'column',
                }}>
                    <AppBar position="static">
                        <Toolbar>
                            {Boolean(menus.length) &&
                                <IconButton
                                    title={menuOpen ? '隐藏菜单' : '显示菜单'}
                                    edge="start" color="inherit"
                                    onClick={handleDrawerToggle}>
                                    {menuOpen ? <ChevronLeftIcon/> : <MenuIcon/>}
                                </IconButton>
                            }
                            <Box sx={{flexGrow: 1}}/>
                            <IconButton color="inherit" title={"用户信息"}
                                        onClick={handleUserinfo}><AccountCircle/></IconButton>
                            <IconButton color="inherit" title={"退出"} onClick={handleLogout}><ExitToApp/></IconButton>
                        </Toolbar>
                    </AppBar>

                    <Tabs sx={{borderBottom: 1, borderColor: 'divider'}} value={activeMenu.key}
                          onChange={handleTabChange} scrollButtons={'auto'} variant="scrollable">
                        {openMenuList.map(menu => (
                            <Tab key={menu.key} value={menu.key}
                                 label={
                                     <Box sx={{display: 'flex', alignItems: 'center', gap: 1}}>
                                         <Typography>{menu.name}</Typography>
                                         {menu.key !== welcome.key &&
                                             <CloseIcon fontSize="small" onClick={(event) => {
                                                 event.stopPropagation();
                                                 handleTabClose(menu.key);
                                             }}/>}
                                     </Box>
                                 }
                            />
                        ))}
                    </Tabs>
                    <Box id="workspace" sx={{flex: 1,}}>{activeMenu.component ?
                        <MyContext.Provider value={{handleMenuClick}}>{activeMenu.component}</MyContext.Provider> :
                        <Todo>{activeMenu.name}</Todo>
                    }</Box>
                </Box>
            </Box>
    );
};

export default App;
